package com.xyhuo.leetcode.january;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 比较版本号
 * https://leetcode.cn/problems/compare-version-numbers/
 *
 * @time 2024/1/29
 */
public class CompareVersion {

//    public static void main(String[] args) {
//        CompareVersion cv=new CompareVersion();
//        cv.compareVersion("1.01","1.001");
//    }

    public int compareVersion(String version1, String version2) {
        List<String> version1List = getVersion(version1);
        List<String> version2List = getVersion(version2);
        int maxLength = Math.max(version1List.size(), version2List.size());
        for (int i = 0; i < maxLength; i++) {
            String tmp1 = "0", tmp2 = "0";
            if (i < version1List.size()) {
                tmp1 = version1List.get(i);
            }
            if (i < version2List.size()) {
                tmp2 = version2List.get(i);
            }
            if (Objects.equals(tmp1, tmp2)) {
                continue;
            }
            Integer tmp1I = Integer.valueOf(tmp1);
            Integer tmp2I = Integer.valueOf(tmp2);
            if (tmp1I > tmp2I) {
                return 1;
            } else {
                return -1;
            }
        }
        return 0;
    }

    private List<String> getVersion(String version) {
        String[] versionCodes = version.split("\\.");
        List<String> versionList = new ArrayList<>();
        for (String code : versionCodes) {
            String tmp = code;
            while (tmp.length() > 0 && tmp.startsWith("0")) {
                tmp = tmp.substring(1);
            }
            versionList.add(tmp.length() > 0 ? tmp : "0");
        }
        return versionList;
    }
}
